<template>
    <div class="app-container">
      <!-- 搜索和操作工具栏 -->
      <div class="filter-container">
        <el-input
          v-model="listQuery.keyword"
          placeholder="请输入关键字"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
        <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
          新增
        </el-button>
        
        <!-- 导入导出组件 -->
        <data-io
          :columns="exportColumns"
          :data="list"
          fileName="请假记录"
          :pdf-options="pdfOptions"
          @import="handleImport"
        />
      </div>
  
      <!-- 数据表格 -->
      <el-table
        :data="list"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="申请人" prop="userName" />
        <el-table-column label="请假类型" prop="leaveType">
          <template slot-scope="{row}">
            {{ getLeaveTypeName(row.leaveType) }}
          </template>
        </el-table-column>
        <el-table-column label="开始时间" prop="startTime" />
        <el-table-column label="结束时间" prop="endTime" />
        <el-table-column label="请假天数" prop="days" />
        <el-table-column label="状态" prop="status">
          <template slot-scope="{row}">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="{row}">
            <el-button type="text" @click="handleUpdate(row)">编辑</el-button>
            <el-button type="text" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
  
      <!-- 编辑表单对话框 -->
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          label-position="left"
          label-width="80px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="请假类型" prop="leaveType">
            <el-select v-model="temp.leaveType" class="filter-item">
              <el-option
                v-for="item in leaveTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="temp.startTime"
              type="datetime"
              placeholder="选择开始时间"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="temp.endTime"
              type="datetime"
              placeholder="选择结束时间"
            />
          </el-form-item>
          <el-form-item label="请假原因" prop="reason">
            <el-input
              v-model="temp.reason"
              type="textarea"
              :rows="4"
              placeholder="请输入请假原因"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确认
          </el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { listLeave, getLeave, addLeave, updateLeave, deleteLeave } from '@/api/leave'
  import Pagination from '@/components/Pagination'
  import DataIO from '@/components/DataIO'
  
  export default {
    name: 'Leave',
    components: { Pagination, DataIO },
    data() {
      return {
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10,
          keyword: undefined
        },
        leaveTypeOptions: [
          { label: '年假', value: 1 },
          { label: '事假', value: 2 },
          { label: '病假', value: 3 },
          { label: '调休', value: 4 }
        ],
        statusOptions: [
          { label: '草稿', value: 0 },
          { label: '待审批', value: 1 },
          { label: '已通过', value: 2 },
          { label: '已拒绝', value: 3 }
        ],
        temp: {
          id: undefined,
          leaveType: 1,
          startTime: undefined,
          endTime: undefined,
          reason: ''
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '新增'
        },
        rules: {
          leaveType: [{ required: true, message: '请选择请假类型', trigger: 'change' }],
          startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
          endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
          reason: [{ required: true, message: '请输入请假原因', trigger: 'blur' }]
        },
        // 导出相关配置
        exportColumns: [
          { prop: 'userName', label: '申请人' },
          { prop: 'leaveType', label: '请假类型' },
          { prop: 'startTime', label: '开始时间' },
          { prop: 'endTime', label: '结束时间' },
          { prop: 'days', label: '请假天数' },
          { prop: 'status', label: '状态' },
          { prop: 'reason', label: '请假原因' }
        ],
        pdfOptions: {
          title: '请假记录',
          table: {
            styles: { cellPadding: 2, fontSize: 8 },
            headerStyles: { fillColor: [41, 128, 185], textColor: 255 }
          }
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        listLeave(this.listQuery).then(response => {
          this.list = response.data.items
          this.total = response.data.total
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleCreate() {
        this.temp = {
          id: undefined,
          leaveType: 1,
          startTime: undefined,
          endTime: undefined,
          reason: ''
        }
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            addLeave(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$message({
                type: 'success',
                message: '创建成功'
              })
              this.getList()
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            updateLeave(tempData).then(() => {
              this.dialogFormVisible = false
              this.$message({
                type: 'success',
                message: '更新成功'
              })
              this.getList()
            })
          }
        })
      },
      handleDelete(row) {
        this.$confirm('确认删除该记录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteLeave(row.id).then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          })
        })
      },
      getLeaveTypeName(type) {
        const found = this.leaveTypeOptions.find(item => item.value === type)
        return found ? found.label : ''
      },
      getStatusName(status) {
        const found = this.statusOptions.find(item => item.value === status)
        return found ? found.label : ''
      },
      getStatusType(status) {
        const map = {
          0: 'info',
          1: 'warning',
          2: 'success',
          3: 'danger'
        }
        return map[status]
      },
      // 处理导入数据
      handleImport(data) {
        // 这里可以处理导入的数据，例如批量创建
        console.log('Imported data:', data)
        this.$message.success(`成功导入 ${data.length} 条数据`)
        this.getList()
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .filter-container {
    padding-bottom: 10px;
    .filter-item {
      margin-right: 10px;
    }
  }
  </style>